package org.jeecg.config.filter;

import com.vdurmont.emoji.EmojiManager;
import com.vdurmont.emoji.EmojiParser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;

public class EmojiWrapper extends HttpServletRequestWrapper {

    /**
     * ENCODING
     */
    private static final String ENCODING = "UTF-8";

    public EmojiWrapper(HttpServletRequest request) {
        super(request);
    }

    /**
     * 字符串去除emoji的方法
     */
    private String convertEmoji2Str(String source) {
        String s = "";
        if(EmojiManager.containsEmoji(source)){
            s= EmojiParser.removeAllEmojis(source);
        }
        return s;
    }

    /**
     * 重写getInputStream方法 post请求参数必须通过流才能获取到值
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {
        String json = "{}";
        try (ServletInputStream stream = super.getInputStream();){
            // 非json类型，直接返回
            if (!MediaType.APPLICATION_JSON_VALUE.equals(super.getHeader(HttpHeaders.CONTENT_TYPE))
                    && !MediaType.APPLICATION_JSON_UTF8_VALUE.equals(super.getHeader(HttpHeaders.CONTENT_TYPE))) {
                return stream;
            }
            // 转化成字符串
            json = IOUtils.toString(stream, ENCODING);

            if (oConvertUtils.isEmpty(json)) {
                return stream;
            }
        } catch (Exception e) {

        }
        //去除表情并返回
        String noEmojiStr = convertEmoji2Str(json);
        // 写回request
        ByteArrayInputStream bis = new ByteArrayInputStream(noEmojiStr.getBytes(ENCODING));

        return new ServletInputStream() {


            @Override
            public int read() throws IOException {
                return bis.read();
            }

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }
        };

    }

}

